<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promiseAPI</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
//    all  全部
//    race 赛跑

//    Promise.all()
//    Promise.race() //赛跑

//Promise.all(iterable);//迭代器  A-> B ->C    Array Set Map => iterable类型

// let pAll = Promise.all([p1,p2,p3]);
/*
* 当p1p2p3都执行完成后,pAll的状态变成已成功, 返回结果为参数顺序
* 当p1p2p3中任意一个失败,pAll的状态都是失败
* */

/*{//
    let p1 = new Promise((resolve, reject)=>{
//        setTimeout(resolve, 3000 ,"p1");
        setTimeout(reject, 3000 ,"p1");
    });
    let p2 = new Promise((resolve, reject)=>{
        setTimeout(resolve, 1000 ,"p2");
    });
    let p3 = new Promise((resolve, reject)=>{
        setTimeout(resolve, 4000 ,"p3");
    });

    //返回的也是一个promise对象
    let pAll = Promise.all([p1,p2,p3]);
/!*    console.log(pAll);
    setTimeout(()=>{
        console.log(pAll);
    }, 7000);*!/

    pAll.then(
        success=>{
            console.log("pAll.then.success====>",success);//数组: ["p1", "p2", "p3"]
            //返回值顺序是和参数顺序一样的, 与请求时长无关
        },
        err=>{
            console.log("pAll.then.err====>",err);//p1
        }
        //一旦有一个promise失败, 那么直接返回触发失败的回调函数,不会再理会其他的promise
    );

    setInterval(()=>{
        console.log(1)
    }, 1000)
}*/

{//
    let p1 = new Promise((resolve, reject)=>{
        setTimeout(resolve, 3000 ,"p1");
//        setTimeout(reject, 3000 ,"p1");
    });
    let p2 = new Promise((resolve, reject)=>{
//        setTimeout(resolve, 1000 ,"p2");
        setTimeout(reject, 1000 ,"p2");
    });
    let p3 = new Promise((resolve, reject)=>{
        setTimeout(resolve, 4000 ,"p3");
    });

    //返回的也是一个promise对象   //racce方法 无论成功还是失败,谁最先有结果 就返回谁
    let pRace = Promise.race([p1,p2,p3]);

    pRace.then(
        success=>{
            console.log("pRace.then.success====>",success);
        },
        err=>{
            console.log("pRace.then.err====>",err);
        }
    );
}

//    resolve
//    reject

//    Promise.resolve(value) 返回一个promise对象
//    Promise.reject() //赛跑

{
    /*$.ajax({
        url: "./data/ajax.txt",
        success(success){
            console.log(success)
        }
    });*/
    Promise.resolve(
        $.ajax({
            url: "./data/ajax.txt"
        })
    ).then(
        success=>{
            console.log(success)
        }
    )
}

{
    let p1 = Promise.resolve(1);
    let p2 = new Promise((resolve, reject)=>{
        resolve(1)
    });
//    p1 等价于 p2
    console.log("p1===>",p1)
    p1.then(
        success=>{
            console.log("p1",success)
        },
        err=>{
            console.log("p1",err)
        }
    );
    p2.then(
        success=>{
            console.log("p2",success)
        },
        err=>{
            console.log("p2",err)
        }
    )
}


</script>
</body>
</html>